//
//  NewsCell.m
//  DaJiang
//
//  Created by sally on 16/9/29.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "ChatManager.h"
#import "DateUtil.h"
#import "NewsCell.h"

@interface NewsCell ()

@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *newsInfoLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeAgoLabel;
@property (weak, nonatomic) IBOutlet UILabel *unReadNumLabel;
@property (weak, nonatomic) IBOutlet UIView *newsUpdateView;
@property (weak, nonatomic) IBOutlet UIImageView *userHeadImage;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *timeLblWidthLayout;

@end

@implementation NewsCell

- (void)awakeFromNib {
  [self initControl];
}

- (void)initControl {
  //未读数view
  self.newsUpdateView.hidden = NO;
  self.newsUpdateView.layer.cornerRadius = 10.0;

  //圆形头像
  self.userHeadImage.layer.masksToBounds = YES;
  self.userHeadImage.layer.cornerRadius = GHeadImageHeight / 2;
}

- (void)setCellConvData:(EMConversation *)conversation {
  EMMessage *msg = [conversation latestMessage];
  id<IEMMessageBody> msgBody = msg.messageBodies.firstObject;

  //内容
  NSString *content;
  if (msgBody.messageBodyType == eMessageBodyType_Image) {//图片类型
    content = @"[图片]";
  }else{
    EMChatText *chat = (EMChatText *) msgBody.chatObject;
    content = chat.text;
  }
  self.newsInfoLabel.text = content;

  ChatExtDB *extDb = [ChatExtDB queryExtByUserName:conversation.chatter];
  UserModel *userM = [CacheManager shareInstance].getLastLoginAccount;
  if (extDb) {
    //头像
    [self.userHeadImage sd_setImageWithURL:[NSURL URLWithString:extDb.avatar] placeholderImage:[UIImage imageNamed:@"ic_default"]];
    //姓名
    self.userNameLabel.text = extDb.nickname;
  } else if (msg.ext) { //如果缓存没有而环信数据库有扩展数据，则将环信的插入到缓存
    if ([[msg.ext valueForKey:@"uid"] integerValue] != userM.uid) {
      Ext *ext = [[Ext alloc] init];
      ext.uid = [msg.ext valueForKey:@"uid"];
      ext.avatar = [msg.ext valueForKey:@"avatar"];
      ext.nickname = [msg.ext valueForKey:@"nickname"];
      ext.username = msg.conversationChatter;
      [ChatManager addExtDateToDB:ext];

      //头像
      [self.userHeadImage sd_setImageWithURL:[NSURL URLWithString:ext.avatar] placeholderImage:[UIImage imageNamed:@"ic_default"]];
      //姓名
      self.userNameLabel.text = ext.nickname;
    }
  }

  //时间
  UIFont *font = GFontWithSize(GNormalFontSize - 1.0);
  self.timeAgoLabel.text = [DateUtil getFormatTime:msg.timestamp];
  //给时间设置宽度，以确认name的宽度
  self.timeLblWidthLayout.constant = [self.timeAgoLabel.text sizeWithAttributes:@{NSFontAttributeName : font}].width + 2;

  //未读
  NSInteger num = [conversation unreadMessagesCount];
  if (num > 0) {
    self.newsUpdateView.hidden = NO;
    self.unReadNumLabel.text = [NSString stringWithFormat:@"%ld", (long) num];
  } else {
    self.newsUpdateView.hidden = YES;
  }
}

@end
